//
//  SVQrcodeDetailController.m
//  ShortVideo-ccinon
//
//  Created by LIN TONG on 2017/6/19.
//  Copyright © 2017年 LIN TONG. All rights reserved.
//

#import "SVQrcodeDetailController.h"
#import "SVNavigationBar.h"
#import "QRCodeUtil.h"
#import "SVConfig.h"
#import "SVQRCode.h"
#import "SVVideo.h"
#import "SVVideoEditViewController.h"
#import "UIActionSheet+Blocks.h"
#import "UIButton+Indexpath.h"
#import "SVAPIReqeust.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "WCLRecordEngine.h"
#import "SVVideoEditViewController.h"
#import "SVUploadProgressView.h"

@interface SVQrcodeDetailController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate>{
    UITableView    *contentTable;
    
    UIView         *footView;
    WCLRecordEngine *recordEngine;
}

@end

@implementation SVQrcodeDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    SVNavigationBar *naviBar = [[SVNavigationBar alloc]init];
    [naviBar setQrcodeHandler:^{
        [QRCodeUtil pushQRCodeVC:self WithCompletionHandler:^(BOOL success, NSString *result) {
            
        }];
    }];
    [naviBar setBackHander:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [naviBar setTitle:self.qrcode.name];
    naviBar.showBackButton = YES;
    [self.view addSubview:naviBar];
    
    contentTable = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(naviBar.frame), __SCREEN_WIDTH__, S(384))];
    contentTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    contentTable.dataSource = self;
    contentTable.delegate = self;
    [self.view addSubview:contentTable];
    
    footView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(contentTable.frame), __SCREEN_WIDTH__, __SCREEN_HEIGHT__-CGRectGetMaxY(contentTable.frame))];
    footView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:footView];
    [self createFootView];
}

- (void)createFootView{
    UIButton *plusButton = [[UIButton alloc]initWithFrame:CGRectMake(S(118), S(10), S(57), S(72))];
    plusButton.center = CGPointMake(__SCREEN_WIDTH__/2.0, plusButton.center.y);
    plusButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 15, 0);
    plusButton.titleLabel.font = Font(11);
    [plusButton setTitleColor:UIColorMake(66, 66, 66, 1) forState:UIControlStateNormal];
    [plusButton setImage:[UIImage imageNamed:@"qr_plus"] forState:UIControlStateNormal];
    [footView addSubview:plusButton];
    
    UILabel *des = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(plusButton.frame)-S(15), __SCREEN_WIDTH__, S(15))];
    des.textAlignment = NSTextAlignmentCenter;
    des.font = [UIFont fontWithName:@"STHeitiSC-Medium" size:12];
    des.textColor = UIColorMake(100, 100, 100, 1);
    des.text = @"点击添加视频";
    [footView addSubview:des];
    
    [plusButton addTarget:self action:@selector(clickPlustButton:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *copyright = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(footView.frame)-S(7)-S(15), __SCREEN_WIDTH__, S(15))];
    copyright.textAlignment = NSTextAlignmentCenter;
    copyright.font = Font(12);
    copyright.textColor = UIColorMake(249, 74, 0, 1);
    copyright.text = @"copyright@ccinon";
    [footView addSubview:copyright];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadVideoLists];
}

- (void)loadVideoLists{
    [SVAPIReqeust svRequestAPI:API(@"/mct/vod/video/lst") method:@"GET" parametors:@{@"vod_qr_id":[NSString stringWithFormat:@"%ld",self.qrcode.ID],@"size":@"20",@"cur":@"1"} completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
        if(success){
            [self.qrcode.videos removeAllObjects];
            NSArray *videoDics = [data objectForKey:@"data"];
            for(NSDictionary *dic in videoDics){
                SVVideo *video = [[SVVideo alloc]init];
                video.fileSize = [[dic objectForKey:@"vod_video_size"]longLongValue];
                video.name = [dic objectForKey:@"vod_video_title"];
                video.des = [dic objectForKey:@"vod_video_describe"];
                video.url = [dic objectForKey:@"vod_video_path"];
                video.videoID = [[dic objectForKey:@"vod_video_id"]integerValue];
                [self.qrcode.videos addObject:video];
            }
            [contentTable reloadData];
        }
    }];
}

- (void)clickMoreButton:(UIButton *)sender{
    [UIActionSheet showInView:self.view withTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"编辑",@"删除视频"] tapBlock:^(UIActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
        
        NSIndexPath *clickPath = sender.indexPath;
        if(buttonIndex == 0){
            SVVideoEditViewController *editVc = [[SVVideoEditViewController alloc]init];
            editVc.state = SV_VIDEO_EDIT;
            editVc.video = self.qrcode.videos[clickPath.row];
            editVc.qrcode = self.qrcode;
            [self.navigationController pushViewController:editVc animated:YES];
        }else if(buttonIndex == 1){
            SVVideo *video = self.qrcode.videos[clickPath.row];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定是否删除" message:video.name preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *OK = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                [alert dismissViewControllerAnimated:YES completion:nil];
                [SVAPIReqeust svRequestAPI:API(@"/mct/vod/video/del") method:@"GET" parametors:@{@"vod_video_id":@(video.videoID)} completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
                    if(success){
                        [self.qrcode.videos removeObjectAtIndex:clickPath.row];
                        [contentTable reloadData];
                    }
                }];
            }];
            
            UIAlertAction *Cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [alert dismissViewControllerAnimated:YES completion:nil];
            }];
            
            [alert addAction:Cancel];
            [alert addAction:OK];
            
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}

- (void)clickPlustButton:(UIButton *)sender{
    UIImagePickerController *moviePicker = [[UIImagePickerController alloc] init];
    moviePicker.delegate = self;
    moviePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    moviePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
    [self presentViewController:moviePicker animated:YES completion:^{
        
    }];
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

#pragma mark - table view delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.qrcode.videos.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return S(64);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = @"identifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell){
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIImageView *iconImage = [[UIImageView alloc]initWithFrame:CGRectMake(S(10), S(7), S(88), S(50))];
        iconImage.tag = 1001;
        iconImage.contentMode = UIViewContentModeScaleAspectFit;
        iconImage.backgroundColor = UIColorMake(30, 30, 30, 1);
        [cell addSubview:iconImage];
        
        UILabel *videoName = [[UILabel alloc]initWithFrame:CGRectMake(S(110), S(8), S(170), S(20))];
        videoName.textColor = UIColorMake(30, 30, 30, 1);
        [videoName setFont:[UIFont fontWithName:@"STHeitiSC-Medium" size:16]];
        videoName.tag = 1002;
        [cell addSubview:videoName];
        
        UIImageView *icon = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMinX(videoName.frame), S(40), S(17), S(10))];
        icon.image = [UIImage imageNamed:@"icon_watch"];
        [cell addSubview:icon];
        
        UILabel *remainCapacity = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(icon.frame)+S(4), S(39), S(150), S(12))];
        remainCapacity.textColor = UIColorMake(100, 100, 100, 1);
        remainCapacity.textAlignment = NSTextAlignmentLeft;
        [remainCapacity setFont:[UIFont fontWithName:@"STHeitiSC-Medium" size:12]];
        remainCapacity.tag = 1006;
        [cell addSubview:remainCapacity];
        
        UIButton *moreButton = [[UIButton alloc]initWithFrame:CGRectMake(__SCREEN_WIDTH__-S(40), 0, S(40), S(25))];
        moreButton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        moreButton.center = CGPointMake(moreButton.center.x, S(32));
        moreButton.tag = 1005;
        [moreButton setImage:[UIImage imageNamed:@"more_info"] forState:UIControlStateNormal];
        [moreButton addTarget:self action:@selector(clickMoreButton:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:moreButton];
        
        UIView *horline = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMinX(videoName.frame), S(64)-S(1), __SCREEN_WIDTH__-S(10)-CGRectGetMinX(videoName.frame), S(1))];
        horline.backgroundColor = UIColorMake(122, 122, 122, 1);
        [cell addSubview:horline];
    }
    
    UIImageView *firstPage = [cell viewWithTag:1001];
    UILabel *name = [cell viewWithTag:1002];
    UILabel *watchCount = [cell viewWithTag:1006];
    UIButton *moreButton = [cell viewWithTag:1005];
    moreButton.indexPath = indexPath;
    
    SVVideo *video = self.qrcode.videos[indexPath.row];
    name.text = video.name;
    watchCount.text = [NSString stringWithFormat:@"观看人数:%ld",video.viewCount];
    
    if(video.firstPage){
        [firstPage setImage:video.firstPage];
    }else{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
            UIImage *image = [SVCommon thumbnailImageForVideo:[NSURL URLWithString:video.url]];
            video.firstPage = image;
            dispatch_async(dispatch_get_main_queue(), ^{
                firstPage.image = image;
            });
        });
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SVVideoEditViewController *videoEdit = [[SVVideoEditViewController alloc]init];
    videoEdit.state = SV_VIDEO_EDIT;
    videoEdit.video = self.qrcode.videos[indexPath.row];
    videoEdit.qrcode = self.qrcode;
    [self.navigationController pushViewController:videoEdit animated:YES];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeMovie]){
        //获取视频的名称
        NSString *videoPath   = [NSString stringWithFormat:@"%@", [info objectForKey:UIImagePickerControllerMediaURL]];
        NSRange range         = [videoPath rangeOfString: @"trim."];//匹配得到的下标
        NSString *content     = [videoPath substringFromIndex: range.location + range.length];
        
        //视频的后缀
        NSRange rangeSuffix   = [content rangeOfString: @"."];
        NSString *suffixName  = [content substringFromIndex: rangeSuffix.location + rangeSuffix.length];
        if ([suffixName isEqualToString: @"MOV"]){
            NSURL *videoUrl = [info objectForKey: UIImagePickerControllerMediaURL];
            
            SVVideoEditViewController *videoEdit = [[SVVideoEditViewController alloc]init];
            SVVideo *video = [[SVVideo alloc]init];
            video.url = [videoUrl absoluteString];
            videoEdit.video = video;
            videoEdit.state = SV_VIDEO_NEW;
            
            videoEdit.qrcode = self.qrcode;
            [self.navigationController pushViewController:videoEdit animated:YES];
        }
    }
}

@end
